<template>
  <div class="report-form">
    <div class="page__header">
      <button class="page__header-btn-back" @click="$router.go(-1)"></button>
      能源换电日报报表
      <button class="page__header-btn-link" @click="$router.go(-1)">专题</button>
    </div>
    <div class="title-bg">
      {{showDate}}能源换电日报报表
      <button type="button" class="title-bg__btn" @click="tipDialog.show = true"></button>
    </div>
    <div class="pd-aside bg-white" style="padding: 8px 10px;">
      <div class="selects">
        <div class="selects__item selects__item--date" @click="chooseDate('city')">
          {{datePickerCity.showData}}
        </div>
        <div class="selects__item" @click="chooseCity('province')">
          {{areaInfo.showArea}}
        </div>
        <div class="selects__item" @click="chooseCity('city')">
          {{cityInfo.showArea}}
        </div>
      </div>
    </div>
    <div class="page__main bg-white">
      <div class="page__scroller">
        <div class="pd-aside" style="height: 100%" v-show="provinceTableData.show">
          <ProvinceTable :data="provinceTableData" v-show="provinceTableData.show"></ProvinceTable>
        </div>
        <div class="pd-aside" style="height: 100%" v-show="cityTableData.show">
          <CityTable :data="cityTableData" v-show="cityTableData.show"></CityTable>
        </div>
        <WaterMark :length="3"></WaterMark>
      </div>
    </div>
    <!-- 开始时间选择器-->
    <van-popup
      v-model="datePickerCity.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-datetime-picker
        v-model="datePickerCity.currentDate"
        ref="city"
        type="date"
        :min-date="datePickerCity.minDate"
        :max-date="datePickerCity.maxDate"
        @cancel="handleCanleDate('city')"
        @confirm="handleConfirmDateCity('city')"
      ></van-datetime-picker>
    </van-popup>
    <van-popup
      v-model="areaInfo.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-picker
        show-toolbar
        :columns="areaInfo.columns"
        :defaultIndex='areaInfo.defaultIndex'
        @cancel="cancelFn('province')"
        @confirm="confirmFnProvince"
      />
    </van-popup>
    <van-popup
      v-model="cityInfo.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-picker
        show-toolbar
        :columns="cityInfo.columns"
        :defaultIndex='cityInfo.defaultIndex'
        @cancel="cancelFn('city')"
        @confirm="confirmFnCity"
      ></van-picker>
    </van-popup>
    <div class="tip-dialog" v-show="tipDialog.show">
      <div class="tip-dialog__main">
        <div class="tip-dialog__header">
          指标说明
          <button type="button" class="tip-dialog__close" @click="tipDialog.show = false"></button>
        </div>
        <div class="tip-dialog__body">
          <div class="tip-dialog__list">
            <div class="tip-dialog__item" v-for="(item, index) in tipDialog.list" :key="index">
              <div class="tip-dialog__item-title">{{item.title}}</div>
              <div class="tip-dialog__item-intro" v-show="item.intro != undefined">{{item.intro}}</div>
              <div class="tip-dialog__item-detail" v-show="item.detail != undefined">{{item.detail}}</div>
            </div>
          </div>
          <div class="footer-tip">了解更多信息，请登录PC端运营数据展示系统</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '@/components/Header'
import WaterMark from '@/components/WaterMark'
import ProvinceTable from "../components/ProvinceTable";
import CityTable from "../components/CityTable";

export default {
  components:{
    Header,
    WaterMark,
    ProvinceTable,
    CityTable,
  },
  data() {
    return {
      pageParams: {
        selectDate: this.$route.query.selectDate,
      },
      userInfo: this.$store.state.userInfo,
      areaId: this.$store.state.userInfo.home_city,
      role: sessionStorage.getItem('role'),
      areaType:'',
      areaProvince1:'100000',
      areaProvince2:'100000',
      areaCity:'0',
      showDate: '',
      passedSort: 'none',
      passedTag: '',
      page: '1',
      total:'',
      pageRows:'96',
      passedChinese:true,
      isProvince:null,
      datePickerCity: {
        showData: '--/--/--',
        selectDate: '',
        show: false,
        currentDate: new Date(),
        minDate: new Date(),
        maxDate: new Date(),
      },
      endDatePickerCity: {
        showData: '--/--/--',
        selectDate: '',
        show: false,
        currentDate: new Date(),
        minDate: new Date(),
        maxDate: new Date(),
      },
      areaInfo: {
        show: false,
        defaultIndex: 0,
        showArea: '',
        selectId: '100000',

        columns: []
      },
      cityInfo: {
        show: false,
        defaultIndex: 0,
        showArea: "地市",
        selectId: "0",
        columns: []
      },
      tableHead:[
        {titile:'地域',width:100},
        {titile:'地域',width:100},
        {titile:'地域',width:100},
        {titile:'地域',width:100},
      ],
      provinceTableData: {
        loading:false,
        show:false,
        showDate:'',
        data:[],
        columnShow:true
      },
      cityTableData: {
        loading:false,
        show:false,
        data:[],
        page:1,
        pageRows:100,
        total:1,
        columnShow:true
      },
      tipDialog: {
        show: false,
        list: [
          {
            title: '注册用户数',
            detail: '历史累计平台内所有用户数合计',
          },
          {
            title: '付费用户数',
            detail: '当前可使用换电服务的用户数'
          },
          {
            title: '本日发展付费用户数',
            detail: '本日新增用户与昨日离网今日续租的用户数合计'
          },
          {
            title: '本日离网付费用户数',
            detail: '套餐到期用户与本日退网的用户数合计',
          },
          {
            title: '本日净增付费用户数',
            intro: '本日发展付费用户-本日离网付费用户'
          },
          {
            title: '本月发展付费用户数',
            detail: '本月每日发展付费用户数合计'
          },
          {
            title: '本月离网付费用户数',
            detail: '本月每日离网付费用户数合计',
          },
          {
            title: '本月净增付费用户数',
            detail: '本月每日净增付费用户数合计'
          },
          {
            title: '本年净增付费用户数',
            detail: '本年每日净增付费用户数合计'
          },
          {
            title: '电池用户比',
            intro: 'C端电池数量/付费用户数',
          },
          {
            title: '活跃人数',
            detail: '本日发生换电的用户数'
          },
          {
            title: '本日换电次数',
            detail: '本日发生换电的次数'
          },
          {
            title: '付费用户与注册用户比',
            intro: '付费用户数/注册用户数'
          },
          {
            title: '日活跃用户与付费用户比',
            intro: '活跃人数/付费用户数',
          },
          {
            title: '户均换电次数',
            intro: '本日换电次数/活跃人数'
          },
          {
            title: '换电成功率',
            intro: '换电成功次数/换电次数'
          },
          {
            title: '电池满足率',
            intro: '1-（没有满电电池出现次数/换电次数）'
          },
          {
            title: '本日行驶里程',
            detail: '本日活跃用户行驶里程合计'
          },
          {
            title: '充放电次数',
            detail: '本日活跃用户充放电次数合计'
          },
          {
            title: 'C端换电站数量',
            detail: 'C端电柜绑定的电站数量合计',
          },
          {
            title: 'C端换电柜数量',
            detail: '设备属性所属客户为“铁塔自用”的设备合计'
          },
          {
            title: 'C端本年净增换电柜数量',
            intro: '本年累计C端换电柜数合计-上年累计C端换电柜数合计'
          },
          {
            title: 'C端仓位数量',
            detail: 'C端电柜的仓位数合计',
          },
          {
            title: 'C端电池数量',
            detail: '设备属性所属客户为“铁塔自用”的设备合计'
          },
          {
            title: 'C端本年净增电池数',
            intro: '本年累计C端电池数合计-上年累计C端电池数合计'
          },
          {
            title: 'B端换电柜数量',
            detail: '设备属性所属客户为非“铁塔自用”的设备合计'
          },
          {
            title: 'B端电池数量',
            detail: '设备属性所属客户为非“铁塔自用”的设备合计'
          },
        ]
      }
    }
  },
  // watch: {
  //   passedSort(newVal) {
  //     if(newVal === 'none') {
  //       this.getTableData('province')
  //       this.getTableData('city')
  //     }
  //   } ,
  //
  // },
  methods: {
    //日期选择
    chooseDate(type) {
        this.datePickerCity.show = true
    },
    //取消日期设置
    handleCanleDate(type) {
        this.datePickerCity.show = false
    },
    //选择日期
    handleConfirmDateCity(state) {
      let currentData = state === 'city' ? 'datePickerCity' : ''
      this[currentData].show = false

      let currentRef = this.$refs[state]
      let value2 = currentRef.value
      let date = new Date(value2)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let month1 = month < 10 ? '0' + month : month
      let day1 = day < 10 ? '0' + day : day
      this[currentData].showData = year + '/' + month + '/' + day
      this[currentData].selectDate = year + '' + month1 + '' + day1
      // TODO 是否需要增加字段区别
      this.showDate = year + '年' + month + '月' + day +'日'
      // TODO 获取数据方法需修改
      this.initPage()
    },
    //获得省分地市
    getAreaInfo() {
      let params = {
        statMonth: this.datePickerCity.selectDate,
        areaId: this.areaId
      }

      this.$http
        .post("api/yearCheckIndex/getKpiAreaInfo", params)
        .then(data => {
          //获取省会
          if (data.rows.length > 1) {
            this.areaInfo.columns = []
            data.rows.forEach(item => {

              this.areaInfo.columns.push({
                text: item.area,
                id: item.areaId
              })
            })
            this.areaInfo.columns.unshift({ text: "全国", id: "100000" })
            this.cityInfo.columns.unshift({ text: "地市", id: "0" })
            this.areaInfo.showArea = '全国'
          }
          // 获取地市
          if (data.rows2.length > 1) {
            this.cityInfo.columns = []
            data.rows2.forEach(item => {
              this.cityInfo.columns.push({
                text: item.area,
                id: item.areaId
              });
            });
            this.cityInfo.columns.unshift({ text: "地市", id: "0" })
            this.areaInfo.selectId = data.rows[0].areaId
            this.areaInfo.showArea = data.rows[0].area
            if (this.role == "province") {
              this.areaInfo.columns.push(
                {
                  text: data.rows[0].area,
                  id: data.rows[0].areaId
                }
              )
              this.areaInfo.defaultIndex = 1
            }
          } else if (data.rows2.length == 1 ) {
            if (this.role == "city") {
              this.areaInfo.selectId = data.rows[0].areaId
              this.areaInfo.showArea = data.rows[0].area
              this.areaInfo.columns = [
                {
                  text: data.rows[0].area,
                  id: data.rows[0].areaId
                }
              ]
              this.cityInfo.selectId = data.rows2[0].areaId
              this.cityInfo.showArea = data.rows2[0].area
              this.cityInfo.defaultIndex = 1
              this.cityInfo.columns = [
                {
                  text: data.rows2[0].area,
                  id: data.rows2[0].areaId
                }
              ]
            }
          }
        });
    },
    //显示地市弹框
    chooseCity(area) {
      if (area == 'province') {
        this.areaInfo.show = true
      } else if (area == 'city') {
        this.cityInfo.show = true
      }
    },
    //取消地市弹框
    cancelFn(area) {
      if (area == 'province') {
        this.areaInfo.show = false
      } else if (area == 'city') {
        this.cityInfo.show = false
      }
    },
    //确认省分
    confirmFnProvince(item, index) {
      if (this.areaInfo.selectId != item.id) {
        this.areaInfo.selectId = item.id
        this.areaId = item.id
        this.areaProvince2=item.id
        this.areaInfo.showArea = item.text
        this.cityInfo.columns = []
        this.cityInfo.showArea = '地市'
        if (this.role == 'province') {
          if (this.areaId != '100000') {
            this.areaInfo.columns = []
            this.getAreaInfo()
          } else {
            this.cityInfo.columns = [{text: '地市', id: '0'}]
          }
        } else {
          this.getAreaInfo()
        }
        this.initPage()
      }
      this.areaInfo.show = false
    },
    //确认地市
    confirmFnCity(item, index) {
      if (this.cityInfo.selectId != item.id) {
        this.cityInfo.selectId = item.id
        this.cityInfo.showArea = item.text
        this.areaCity=item.id
        if (this.cityInfo.selectId != '' && this.cityInfo.selectId != 0) {
          this.areaId = item.id
        } else {
          this.areaId = this.areaInfo.selectId
        }
          this.initPage()
      }
      this.cityInfo.show = false
    },
    //获得时间域
    getMaxMinMonth() {
      function dateSplit(param) {
        let paramStr = param + ''
        let dateStr = paramStr.replace(/(.{2})/g,'$1,')
        let dateArr = dateStr.substr(0, dateStr.length - 1).split(',')
        return dateArr
      }
      let params = {
        type:'day',
        process_name:'MKT_SUM_MOA_HOMEPAGE_DAY',
        partion_id:75
      }
      return new Promise((resolve, reject) => {
        this.$http.post('/api/moaVisit/getMaxTime', params).then(data => {
          let max_time=data.STAT_DATE
          let max = max_time.substring(0, 4) + max_time.substring(5, 7) + max_time.substring(8);
          let min = 20211220

          let maxYear = dateSplit(max)[0] + dateSplit(max)[1]
          let maxMonth = dateSplit(max)[2]
          let maxDay= dateSplit(max)[3]
          let minYear = dateSplit(min)[0] + dateSplit(min)[1]
          let minMonth = dateSplit(min)[2]
          let minDay= dateSplit(min)[3]
          let actualMaxMonth = parseInt(maxMonth) - 1
          let actualMinMonth = parseInt(minMonth) - 1

          let minDate = new Date(minYear, actualMinMonth, minDay)
          let maxDate = new Date(maxYear, actualMaxMonth, maxDay)

          let paramsDate = this.pageParams.selectDate
          let paramsYear = dateSplit(paramsDate)[0] + dateSplit(paramsDate)[1]
          let paramsMonth = dateSplit(paramsDate)[2]
          let paramsDay = dateSplit(paramsDate)[3]
          let paramsActualMonth = parseInt(paramsMonth) - 1
          let paramsShowMonth = paramsMonth[0] == '0' ? paramsMonth[1] : paramsMonth
          let paramsShowDay = paramsDay[0] == '0' ? paramsDay[1] : paramsDay
          let showData = paramsYear + '/' + paramsShowMonth + '/' + paramsShowDay
          let paramsCurrent = new Date(paramsYear, paramsActualMonth, paramsDay)

          this.datePickerCity.currentDate = paramsCurrent
          this.datePickerCity.minDate = minDate
          this.datePickerCity.maxDate = maxDate
          this.datePickerCity.showData = showData
          this.datePickerCity.selectDate = paramsDate

          this.showDate = paramsYear + '年' + paramsShowMonth + '月' + paramsShowDay +'日'
          resolve("ok")
        })
      })
    },
    //获得省分、地市表格数据
    getTableData(type) {
      if(type=='province'){
        let params = {
          statDate: this.datePickerCity.selectDate,
          areaId: this.areaId,
          areaType: this.areaType,
        }
        this.provinceTableData.data = []
        this.provinceTableData.loading = true
        this.provinceTableData.show=true;
        this.cityTableData.show=false;
        this.$http.post('/api/energyExchangeDailyNew/qryReportList', params).then(data => {
          this.provinceTableData.data = data.list;
          this.provinceTableData.loading = false
        })
      }else if(type=='city'){
        let params = {
          statDate: this.datePickerCity.selectDate,
          areaId: this.areaId,
          areaType: this.areaType,
        }
        this.cityTableData.data = []
        this.cityTableData.loading = true
        this.cityTableData.show=true;
        this.provinceTableData.show=false;
        this.$http.post('/api/energyExchangeDailyNew/qryReportList', params).then(res => {
            this.cityTableData.data = res.list;
            this.cityTableData.loading = false
          });
      }
    },
    nextText(){
      //重新刷新页面数据
      this.getTableData('city');
    },
    //报表跳转
    jump(){
      this.$router.push({
        path:'/ReportFormDetailSpecial'
      })
    },
    //页面初始化
    initPage() {
      if(this.areaId=='100000'){
        this.areaType = 0;

        this.cityTableData.show=false;
      }else if(this.areaId.substr(-4) == '0000'){
        this.areaType = 1;
      }else {
        this.areaType = 2;
      }
      if(this.areaType == 0) {
        this.getTableData('province')
      }else{
        this.cityTableData.page = 1;
        this.getTableData('city')
      }
    },
    //记录日志
    recordLogs() {
      let params = {
        userId: this.userInfo.user_id,
        verify_code: this.userInfo.verify_code,
        priv_id: '10102122',
      }

      this.$http.post('api/new/insertLogs', params).then(res => {})
    },
  },
  mounted() {
    this.recordLogs()
    this.getAreaInfo()
    this.getMaxMinMonth().then(res => {
      if (res == 'ok') {
        this.initPage()
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    if (to.name == 'ReportFormDetail') {
      let formCharge = {
        selectDate: this.datePickerCity.selectDate,
      }
      sessionStorage.setItem('formCharge', JSON.stringify(formCharge))
    } else {
      sessionStorage.removeItem('formCharge')
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.jump{
  position: absolute;
  top: 0;
  right: 20px;
  z-index: 1;
  color: #666666;
  cursor: pointer;
  .jump__icon{
    display: inline-block;
    width: 14px;
    height: 14px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    margin-right: 2px;
    background-image: url(~@/assets/images/icon-link.png);
  }
}
.selects {
  margin-bottom: 0;

  &__item--date {
    flex: 1;
    width: 34%;
  }
  &__item--date1 {
    flex: 2;
    width: 34%;
  }
}

.tabs {
  display: flex;
  height: 32px;

  &__item {
    flex: 1;
    text-align: center;
    line-height: 32px;
    background: #fff;
    font-size: 14px;
    position: relative;

    &--current::before {
      content: "";
      position: absolute;
      width: 32px;
      height: 2px;
      background: #d9001b;
      bottom: 0;
      left: 50%;
      margin-left: -16px;
    }
  }
}

.checks {
  padding-bottom: 5px;
  padding-left: 80px;

  &__name {
    float: left;
    margin-left: -70px;
  }

  .van-checkbox-group {
    display: flex;
  }

  .van-checkbox + .van-checkbox{
    margin-left: 10px;
  }
}

.report-form {
  .title-bg {
    line-height: 3;
    padding-top: 18px;
    box-sizing: border-box;
    font-size: 18px;
  }
  .water-mark {
    z-index: 1;
  }
}
.select-date {
  -webkit-box-flex: 2;
  flex: 2;
}
.select-address {
  -webkit-box-flex: 1;
  flex: 1;
}
/deep/ .van-pagination__item{
  color:#ff716b;
}
/deep/ .van-pagination__item--disabled{
  color: #646566;
}
/deep/ .van-pagination__item:active{
  color:#ff716b;
  background:none;
}
</style>
